package cn.rtplay.esp32camcar.downloadApk;

import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ProviderInfo;
import android.os.Build;

import androidx.core.content.FileProvider;

import java.io.File;
import java.io.InputStream;
import java.util.Objects;
import java.util.concurrent.Callable;

import cn.rtplay.esp32camcar.toolUtils.LogUtil;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

import static cn.rtplay.esp32camcar.downloadApk.AppUtil.sApp;


/**
 * 作者:王浩 邮件:bingoogolapple@gmail.com
 * 创建时间:16/12/16 上午10:48
 * 描述:应用升级工具类
 */
public class BGAUpgradeUtil {
    private static final String MIME_TYPE_APK = "application/vnd.android.package-archive";
    private static final String TAG = "BGAUpgradeUtil";

    private BGAUpgradeUtil() {
    }

    /**
     * 监听下载进度
     *
     * @return Observable对象
     */
    public static Observable<BGADownloadProgressEvent> getDownloadProgressEventObservable() {
        return RxUtil.getDownloadEventObservable();
    }

    /**
     * apk 文件是否已经下载过，如果已经下载过就直接安装
     *
     * @param version 新 apk 文件版本号
     * @return 文件存在为true并且安装，不存在为false
     */
    public static boolean isApkFileDownloaded(String version) {
        File apkFile = StorageUtil.getApkFile(version);
        if (apkFile.exists()) {
            installApk(version);
            return true;
        }
        return false;
    }

    /**
     * 下载新版 apk 文件
     *
     * @param url     apk 文件路径
     * @param version 新 apk 文件版本号
     * @return Observable对象
     */
    public static Observable<File> downloadApkFile(final String url, final String version) {
        return Observable.defer((Callable<Observable<InputStream>>) () -> {
            try {
                return Observable.just(Objects.requireNonNull(Engine.getInstance().getDownloadApi().downloadFile(url).execute().body()).byteStream());
            } catch (Exception e) {
                return Observable.error(e);
            }
        }).map(inputStream -> StorageUtil.saveApk(inputStream, version))
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread());
    }

    /**
     * 安装 apk 文件
     *
     * @param version 新 apk 文件版本号
     */
    public static void installApk(String version) {
        Intent installApkIntent = new Intent();
        installApkIntent.setAction(Intent.ACTION_VIEW);
        installApkIntent.addCategory(Intent.CATEGORY_DEFAULT);
        installApkIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

        installApkIntent.setDataAndType(FileProvider.getUriForFile(sApp, sApp.getPackageName()+".fileprovider", StorageUtil.getApkFile(version)), MIME_TYPE_APK);
        installApkIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);

        if (sApp.getPackageManager().queryIntentActivities(installApkIntent, 0).size() > 0) {
            sApp.startActivity(installApkIntent);
        }
    }

    /**
     * 获取FileProvider的auth
     *
     * @return 授权
     */
    private static String getFileProviderAuthority() {
        try {
            LogUtil.v(TAG, "getFileProviderAuthority: in->"+sApp.getPackageName());
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                //是否有安装位置来源的权限
                boolean haveInstallPermission = sApp.getPackageManager().canRequestPackageInstalls();
                LogUtil.d(TAG, "getFileProviderAuthority: "+haveInstallPermission );
            }

            for (ProviderInfo provider : sApp.getPackageManager().getPackageInfo(sApp.getPackageName(), PackageManager.GET_PROVIDERS).providers) {
                LogUtil.d(TAG, "getFileProviderAuthority provider.name: "+provider.name );
                LogUtil.d(TAG, "getFileProviderAuthority FileProvider.name: "+FileProvider.class.getName() );
                if (FileProvider.class.getName().equals(provider.name) && provider.authority.endsWith(".demo.file_provider")) {
                    LogUtil.d(TAG, "getFileProviderAuthority: "+provider.authority);
                    return provider.authority;
                }
            }
        } catch (PackageManager.NameNotFoundException ignore) {
            LogUtil.e(TAG, "getFileProviderAuthority: catch");
        }
        LogUtil.v(TAG, "getFileProviderAuthority: null");
        return null;
    }

    /**
     * 删除之前升级时下载的老的 apk 文件
     */
    public static void deleteOldApk() {
        File apkDir = StorageUtil.getApkFileDir();
        if (apkDir == null || apkDir.listFiles() == null || Objects.requireNonNull(apkDir.listFiles()).length == 0) {
            return;
        }
        LogUtil.d(TAG, "---deleteOldApk: "+apkDir.getAbsolutePath() );
        // 删除文件
        StorageUtil.deleteFile(apkDir);
    }

    /**
     * 删除之前升级时下载的老的 apk 文件
     */

    public static void deleteOldApk(String version) {
        File apkDir = StorageUtil.getApkFileDir();
        if (apkDir == null || apkDir.listFiles() == null || Objects.requireNonNull(apkDir.listFiles()).length == 0) {
            return;
        }
        File apkFile = new File(apkDir.getAbsolutePath()+"/esp32car_V"+version+".apk");
        LogUtil.d(TAG, "---deleteOldApk: "+apkFile.getAbsolutePath() );
        // 删除文件
        StorageUtil.deleteFile(apkFile);
    }

    /**
     * apk下载完成之后，将.tmp后缀去掉
     */
    public static void completeDownloadAPK(String version) {
        StorageUtil.completeDownloadAPK(version);
    }
}
